<!-- 元数据编辑对话框 -->
<template>
  <CommonDialog
    v-model="visible"
    :title="`${metadataId ? '编辑' : '创建'}数据源`"
    :width="500"
    :loading="loading"
    @submit="submit"
    @cancel="cancel"
  >
    <OptionForm
      ref="formRef"
      v-model="formData"
      :key="formKey"
      :fields="formFields"
      :config="formConfig"
    />
  </CommonDialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Message } from 'view-ui-plus'

import { dataSource } from '@/api/modules/modelSetting'
import OptionForm from '@/components/OptionForm/index.vue'

const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

// 表单元素ref
const formRef = ref(null)

// 元数据ID
const metadataId = ref(undefined)

const SQL_OPTIONS = [
  { label: 'MySQL', value: 'mysql' },
  { label: 'Oracle', value: 'oracle' }
]

const formKey = ref(0)

// 表单数据
const formData = ref({
  name: '',   
  databasetype: SQL_OPTIONS[0].value,   
  account: '',   
  password: '', 
  driverclazz: '',   
  databaseurl: ''
})

// 表单字段配置
const formFields = computed(() => ({
  name: {
    type: 'input',
    label: '数据源名称',
    required: true,
    clearable: true
  },
  databasetype: {
    type: 'select',
    label: '数据库类型',
    required: true,
    options: SQL_OPTIONS,
    transfer: true
  },
  account: {
    type: 'input',
    label: '访问账号',
    required: true,
    clearable: true
  },
  password: {
    type: 'input',
    label: '密码',
    inputType: 'password',
    required: true
  },
  driverclazz: {
    type: 'input',
    label: '驱动接口',
    required: true,
    clearable: true
  },
  databaseurl: {
    type: 'textarea',
    label: '链接地址',
    required: true,
    rows: 4
  }
}))

// 表单配置
const formConfig = ref({
  labelWidth: 120,
  labelPosition: 'right',
  labelColon: true
})

/**
 * 提交表单
 */
const submit = async () => {
  // 验证表单
  const formData = await formRef.value.validate()

  loading.value = true
    
  try {
    await dataSource[metadataId.value ? 'edit' : 'add']({
      data: {
        ...formData,
        id: metadataId.value
      }
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const getDetailData = () => {
  loading.value = true

  dataSource.detail({
    data: {
      id: metadataId.value
    }
  }).then(({data})=>{
    for(const key in formData.value) {
      if(key === 'password') continue

      formData.value[key] = data[key]
    }

    formRef.value.clearValidate()
  }).finally(()=>{
    loading.value = false
  })
}

/**
 * 初始化对话框
 */
const initDialog = (id) => {
  // 显示对话框
  visible.value = true

  metadataId.value = id

  if (id) {
    formFields.value.password.required = false
    formKey.value++
    getDetailData()
  }

  // 清除表单验证状态
  setTimeout(() => {
    if (formRef.value && typeof formRef.value.clearValidate === 'function') {
      formRef.value.clearValidate()
    }
  }, 100)
}

defineExpose({
  initDialog
})
</script>